import { request, toPromise, uploadFile } from "../../utils/http"
import { isEmpty } from "../../utils/util"

Page({
  data: {
    form: {}
  },

  updateForm (e) {
    const { detail, target } = e
    const { field, type } = target.dataset
    const { value } = detail
    this.setData({
      [`form.${field}`]: type === 'number' ? +value : value
    })
  },

  goLogin () {
    wx.redirectTo({
      url: '/pages/login/index',
    })
  },

  getWxUser () {
    toPromise(wx.getUserProfile, {
      desc: '获取您的信息用于自动填写表单。'
    }).then(data => {
      const { userInfo: user } = data
      this.setData({
        form: {
          nickname: user.nickName,
          avatar: user.avatarUrl,
          gender: { 1: 1, 2: 0 }[user.gender]
        }
      })
    })
  },

  selectAvatar () {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      success: res => {
        console.log(res)
        const file = res.tempFiles[0]
        const fileName = file.tempFilePath.split('/').pop()
        uploadFile({ file, dest: `/avatar/${Date.now()}-${fileName}` }).then(data => {
          console.log(data)
        })
      }
    })
  },

  userRegister () {
    const { nickname, name } = this.data.form
    if (isEmpty(nickname) || !nickname.trim()) {
      return wx.showToast({ title: '请填写昵称', icon: 'error' })
    }
    if (isEmpty(name) || !name.trim()) {
      return wx.showToast({ title: '请填写真实姓名', icon: 'error' })
    }
    wx.showLoading({ title: '请稍后...' })
    request({
      url: '/api/portal/register',
      method: 'POST',
      saveToken: true,
      data: this.data.form
    }).then(() => {
      wx.hideLoading()
      wx.switchTab({
        url: '../../pages/home/index'
      })
    }).catch(async e => {
      await wx.hideLoading()
    })
  },

  onLoad (options) {
    const user = options.userJson ? JSON.parse(options.userJson) : {}
    this.setData({
      form: user
    })
  }
})
